package cn.abcsys.cloud.devops.web.controller;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.abcsys.cloud.devops.web.entity.GridBean;
import cn.abcsys.cloud.devops.web.entity.PagerModel;
import cn.abcsys.cloud.devops.web.entity.User;
import cn.abcsys.cloud.devops.web.service.UserService;
import cn.abcsys.cloud.devops.web.util.HashUtil;
import cn.abcsys.cloud.devops.web.util.Result;


/**
 * 用户信息控制
 * @author xzg
 *
 */
@RestController
@RequestMapping("/user")
public class UserController {
	private static final Logger LOGGER = Logger.getLogger(UserController.class);
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/list", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public GridBean getUsers(HttpServletRequest request, @RequestBody Map<String, Object> params){
		
		if(null == params){
			LOGGER.error("请求参数为空");
			return null;
		}else{
			try{
				 JSONObject paramIn=new JSONObject(params);  //map转对象
				User loginUser = (User)request.getSession().getAttribute("user");
				Integer envId = (Integer)request.getSession().getAttribute("envId");
				if(null == loginUser)
					return null;
				
				//net.sf.json.JSONArray paramIn = net.sf.json.JSONArray.fromObject(params);
				PagerModel pagerModel = paramIn.toJavaObject(PagerModel.class);
				Map<String, Object> map = new HashMap<>();
				map.put("userName", paramIn.getString("userName"));
				map.put("roleName", paramIn.getString("roleName"));
				map.put("userStatus", paramIn.getString("userStatus"));
				//
				map.put("envId", envId);
				map.put("userCreator", loginUser.getUserId());
				map.put("isAdmin", loginUser.getIsAdmin());
				return userService.getUsers(map,pagerModel);
			}catch(Exception e){
				LOGGER.error("请求参数转换错误："+e.getMessage());
				return null;
			}
		}
	}
	
	/**
	 * 查询当前环境用户的详细信息
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/detail", method = { RequestMethod.POST })
	@ResponseBody
	public Result getUserDetail(HttpServletRequest request,@RequestBody Map<String, Integer> map){
		Map<String,Object> userInfo = null;
		Integer userId = map.get("userId");
		Integer envId = (Integer)request.getSession().getAttribute("envId");
		User loginUser = (User)request.getSession().getAttribute("user");
		if(null == userId || null == envId||null == loginUser)
			return new Result(false, "用户信息失效");
		Byte isAdmin = loginUser.getIsAdmin();
		Byte admin = (byte)1;
		//如果不是超级管理员，添加当前环境信息环境信息
		if(!admin.equals(isAdmin)){
			map.put("envId", envId);
		}
		userInfo = userService.getUserDetail(map);
		if(null == userInfo)
			return new Result(false,"当前无查询结果");
		return new Result(true, userInfo, "成功返回结果");
	}
	
	/**
	 * 创建用户
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/create", method = { RequestMethod.POST })
	@ResponseBody
	public Result insertUser(@RequestBody User user,HttpServletRequest request){
		//当前在线的用户
		User loginUser = (User) request.getSession(true).getAttribute("user");
		if(null == loginUser)
			return new Result(false, "您已不在线，请再次登录");;
		int re = 0;//标识执行成功与否
		//没有设置密码，则默认密码123456
		String password = null == user.getUserPass()?"123456":user.getUserPass();
		Integer userCreator= loginUser.getUserId();
		user.setUserCreator(userCreator);
		user.setUserPass(HashUtil.md5Hash(password));
		//这里需要判断是否已存在
		user.setLdapUid(user.getUserName());
		//1、该用户如果为超级管理员，则不存在默认环境的情况，否则必须制指定当前操作的环境为该用户的默认环境
		if(null != user.getIsAdmin() && 1 == user.getIsAdmin()){
			re = userService.insert(user);
		}else{//该用户为其他用户需要指定当前环境为默认环境
			if(null == user.getDefaultEnvId())
				return new Result(false, "请先确定用户所处环境信息");
			re = userService.insert(user);
		}
		if( 0 != re)
			return new Result(true, "创建用户成功");
		else
			return new Result(false, "创建用户失败");
	}
	/**
	 * 修改用户信息
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/updateUser", method = { RequestMethod.POST })
	@ResponseBody
	public Result updateUser(@RequestBody User user){
		
		int re = userService.updateUserByUserId(user);
		if( 0 != re)
			return new Result(true, "修改用户成功");
		else
			return new Result(false, "修改用户失败");
	}	
	/**
	 * 删除用户
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/delete", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Result deleteUser(HttpServletRequest request,@RequestBody Map<String, Integer> map){
		Result result = new Result();
		if(null == map)
			return new Result(false, "删除用户失败");
		Integer userId = map.get("userId");
		try {
			result.setMessage("删除成功");
			result.setSuccess(true);
			userService.delete(userId);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			result.setMessage("删除失败");
			result.setSuccess(false);
			
		}
		return result;
	}		
	
	/**
	 * 获取普通用户信息
	 * @param request
	 * @param envId
	 * @return
	 */
	@RequestMapping(value = "/getOrdinaryleUser", method = { RequestMethod.GET})
	@ResponseBody
	public Result getOrdinaryleUser(HttpServletRequest request,@RequestParam("envId") Integer envId){
		
		List<User> list = userService.getOrdinaryleUser(envId);
		if(null == list || 0 == list.size())
			return new Result(false, "无返回结果！");
		else
			return new Result(true, list, "操作成功");
	}

	/**
	 * 环境下查看项目管理员
	 * @param request
	 * @param envId
	 * @return
	 */
	@RequestMapping(value = "/getprojectUser", method = { RequestMethod.GET})
	@ResponseBody
	public Result getprojectUser(HttpServletRequest request,@RequestParam("envId") Integer envId){
		
		List<User> list = userService.getProjectUser(envId);
		if(null == list || 0 == list.size())
			return new Result(false, "无返回结果！");
		else
			return new Result(true, list, "操作成功");
	}
	
	@RequestMapping(value = "/change", method={RequestMethod.POST})
	@ResponseBody
	public Result changePassword(HttpSession session,@RequestBody Map<String, String> map){
		if(null == session || null == session.getAttribute("user"))
				return new Result(false, "会话失效请重新登录！");
			User loginUser = (User) session.getAttribute("user");
			String oldPassword = map.get("oldPassword");
			String password = map.get("password");
			//String userId = map.get("id");
			//1 查询用户账号密码是否一致
			loginUser.setUserPass(HashUtil.md5Hash(oldPassword));
			if(userService.checkUser(loginUser))
				return new Result(false, "原密码输入不正确");
			//2 修改密码
			loginUser.setUserPass(HashUtil.md5Hash(password));
			int re = userService.updateUserByUserId(loginUser);
			if(0 == re)
				return new Result(false, "密码修改失败");
			else
				return new Result(true, "密码修改成功");
	}
	/**
	 * 获取普通用户信息
	 * @param request
	 * @param envId
	 * @return
	 */
	@RequestMapping(value = "/getEnvUser", method = { RequestMethod.GET})
	@ResponseBody
	public Result getEnvUser(HttpServletRequest request){
		
		List<User> list = userService.getEnvUser();
		if(null == list || 0 == list.size())
			return new Result(false, "无返回结果！");
		else
			return new Result(true, list, "操作成功");
	}
	
	@RequestMapping(value="/lock",method={RequestMethod.POST})
	@ResponseBody
	public Result lockUser(@RequestBody Map<String, Integer> map){
		Integer userId = map.get("id");
		if(null == userId)
			return new Result(false, "冻结用户失败");
		int re = userService.lockUser(userId);
		if(0==re)
			return new Result(false, "冻结用户失败");
		
		return new Result(true, "冻结用户成功");
	}
	
}
